import random
from math import sin, cos, pi, log, sqrt
from tkinter import *
import time

CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
CANVAS_CENTER_X = CANVAS_WIDTH / 2
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2
IMAGE_ENLARGE = 11

COLORS = ["#64FEDA", "#45B7D1", "#4ECDC4", "#96CEB4", "#A7FFEB"]
HEART_COLOR = "#45B7D1"
BG_COLOR = "#0A1929"
TEXT_COLOR = "#E0F7FA"
SUB_TEXT_COLOR = "#80DEEA"


def center_window(root, width, height):
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    root.geometry(size)


def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):

    x = 16 * (sin(t) ** 3)
    y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
    x *= shrink_ratio
    y *= shrink_ratio
    x += CANVAS_CENTER_X
    y += CANVAS_CENTER_Y
    return int(x), int(y)


def scatter_inside(x, y, beta=0.15):
    ratio_x = - beta * log(random.random())
    ratio_y = - beta * log(random.random())
    dx = ratio_x * (x - CANVAS_CENTER_X)
    dy = ratio_y * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def shrink(x, y, ratio):
    force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6)
    dx = ratio * force * (x - CANVAS_CENTER_X)
    dy = ratio * force * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def curve(p):
    # 更复杂的曲线函数，创造更丰富的动画效果
    return 2 * (2 * sin(4 * p) + 0.5 * sin(8 * p)) / (2 * pi)


def get_gradient_color(progress):

    idx = int(progress * (len(COLORS) - 1))
    return COLORS[idx]


class Particle:
    def __init__(self, x, y, size, color, velocity_x=0, velocity_y=0, life=100):
        self.x = x
        self.y = y
        self.size = size
        self.color = color
        self.velocity_x = velocity_x
        self.velocity_y = velocity_y
        self.life = life
        self.max_life = life


class AdvancedHeart:
    def __init__(self, generate_frame=30):
        self._points = set()
        self._edge_diffusion_points = set()
        self._center_diffusion_points = set()
        self.all_points = {}
        self.particles = []
        self.build(3000)
        self.random_halo = 1500
        self.generate_frame = generate_frame
        for frame in range(generate_frame):
            self.calc(frame)

    def build(self, number):
        # 构建基础心形点
        for _ in range(number):
            t = random.uniform(0, 2 * pi)
            x, y = heart_function(t)
            self._points.add((x, y))

        # 边缘扩散点
        for _x, _y in list(self._points):
            for _ in range(4):
                x, y = scatter_inside(_x, _y, 0.03)
                self._edge_diffusion_points.add((x, y))

        # 中心扩散点
        point_list = list(self._points)
        for _ in range(6000):
            x, y = random.choice(point_list)
            x, y = scatter_inside(x, y, 0.12)
            self._center_diffusion_points.add((x, y))

    @staticmethod
    def calc_position(x, y, ratio):
        force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520)
        dx = ratio * force * (x - CANVAS_CENTER_X) + random.uniform(-1.5, 1.5)
        dy = ratio * force * (y - CANVAS_CENTER_Y) + random.uniform(-1.5, 1.5)
        return x - dx, y - dy

    def create_particles(self, x, y, count=3):

        for _ in range(count):
            velocity_x = random.uniform(-2, 2)
            velocity_y = random.uniform(-2, 2)
            size = random.randint(1, 3)
            color = random.choice(COLORS)
            particle = Particle(x, y, size, color, velocity_x, velocity_y)
            self.particles.append(particle)

    def update_particles(self):

        new_particles = []
        for particle in self.particles:
            particle.x += particle.velocity_x
            particle.y += particle.velocity_y
            particle.life -= 1
            particle.velocity_y += 0.1  # 重力效果

            if particle.life > 0:
                new_particles.append(particle)
        self.particles = new_particles

    def calc(self, generate_frame):
        ratio = 12 * curve(generate_frame / 12 * pi)
        halo_radius = int(6 + 8 * (1 + curve(generate_frame / 12 * pi)))
        halo_number = int(4000 + 6000 * abs(curve(generate_frame / 12 * pi) ** 2))

        all_points = []
        heart_halo_point = set()

        # 彩色光环效果
        for _ in range(halo_number):
            t = random.uniform(0, 2 * pi)
            x, y = heart_function(t, shrink_ratio=12.8)
            x, y = shrink(x, y, halo_radius)
            if (x, y) not in heart_halo_point:
                heart_halo_point.add((x, y))
                x += random.randint(-16, 16)
                y += random.randint(-16, 16)
                size = random.choice((1, 2, 3))
                color_progress = (generate_frame % 60) / 60
                color = get_gradient_color(color_progress)
                all_points.append((x, y, size, color))

        # 心形轮廓
        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 4)
            all_points.append((x, y, size, HEART_COLOR))

        # 边缘扩散点
        for x, y in self._edge_diffusion_points:
            x, y = self.calc_position(x, y, ratio * 0.7)
            size = random.randint(1, 3)
            all_points.append((x, y, size, "#FFB6C1"))

        # 中心扩散点
        for x, y in self._center_diffusion_points:
            x, y = self.calc_position(x, y, ratio * 0.5)
            size = random.randint(1, 2)
            all_points.append((x, y, size, "#FF69B4"))

        self.all_points[generate_frame] = all_points


        if generate_frame % 5 == 0:
            for _ in range(10):
                t = random.uniform(0, 2 * pi)
                x, y = heart_function(t, shrink_ratio=13)
                self.create_particles(x, y, 2)

    def render(self, render_canvas, render_frame):
        # 清空画布
        render_canvas.delete('all')

        # 渲染背景星空
        self.render_stars(render_canvas)

        # 渲染心形点
        frame_data = self.all_points.get(render_frame % self.generate_frame, [])
        for x, y, size, color in frame_data:
            render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=color)

        # 渲染粒子
        self.render_particles(render_canvas)
        self.update_particles()

    def render_stars(self, render_canvas):

        for _ in range(50):
            x = random.randint(0, CANVAS_WIDTH)
            y = random.randint(0, CANVAS_HEIGHT)
            size = random.randint(1, 2)
            brightness = random.randint(100, 255)
            color = f"#{brightness:02x}{brightness:02x}{brightness:02x}"
            render_canvas.create_oval(x, y, x + size, y + size, fill=color, outline="")

    def render_particles(self, render_canvas):

        for particle in self.particles:
            alpha = particle.life / particle.max_life
            render_canvas.create_oval(
                particle.x, particle.y,
                particle.x + particle.size,
                particle.y + particle.size,
                fill=particle.color, outline="", stipple="gray50"
            )


def draw(main: Tk, render_canvas: Canvas, render_heart: AdvancedHeart, render_frame=0):
    render_canvas.delete('all')
    render_heart.render(render_canvas, render_frame)
    main.after(80, draw, main, render_canvas, render_heart, render_frame + 1)


if __name__ == '__main__':
    root = Tk()
    root.title(".")
    root.configure(bg='black')
    center_window(root, CANVAS_WIDTH, CANVAS_HEIGHT)

    canvas = Canvas(root, bg='#0a0a2a', height=CANVAS_HEIGHT, width=CANVAS_WIDTH, highlightthickness=0)
    canvas.pack()

    heart = AdvancedHeart()

    text_label = Label(root, text="祝你开心，不止今天",
                       bg='#0a0a2a', fg='white',
                       font=("Microsoft YaHei", 24, "bold"),
                       relief='flat')
    text_label.place(relx=.5, rely=.5, anchor=CENTER)

    sub_label = Label(root, text="生日快乐",
                      bg='#0a0a2a', fg='#FFB6C1',
                      font=("Microsoft YaHei", 12, "italic"))
    sub_label.place(relx=.5, rely=.6, anchor=CENTER)

    draw(root, canvas, heart)
    root.mainloop()